import React, { useEffect, useState } from 'react';
import { Card, message } from 'antd';
import axios from "axios";
import { useNavigate } from 'react-router-dom'; // 导入 useNavigate
import './words.css';

interface Harp {
    attributes: string;
    one: string;
    id: number;
    title: string;
    attribute: number;
}

const HarpList: React.FC = () => {
    const [harpList, setHarpList] = useState<Harp[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [filterAttribute, setFilterAttribute] = useState<number | null>(null);
    const token = localStorage.getItem('token');
    const navigate = useNavigate(); // 使用 useNavigate

    // 获取所有Harp数据的函数
    const fetchHarpAll = async () => {
        try {
            let url = 'api/harp/all';
            if (filterAttribute !== null) {
                url += `?attribute=${filterAttribute}`;
            }
            const response = await axios.get<Harp[]>(url, {
                headers: {
                    Authorization: `Bearer ${token}`,
                },
            });
            setHarpList(response.data);
            setIsLoading(false);
        } catch (err) {
            setIsLoading(false);
            message.error('获取词典数据失败，请稍后再试。');

        }
    };

    useEffect(() => {
        fetchHarpAll();
    }, [filterAttribute]);

    const handleFilter = (value: number) => {
        setFilterAttribute(value);
    };

    const handleCardClick = (id: number) => {
        navigate(`/harpdetails/${id}`); // 假设详情页面的路径是 /details/:id
    };

    return (
        <div>
            {isLoading && <p>正在加载词典数据...</p>}
            {!isLoading && (
                <div className="harp-cards-container"
                     style={{ display: 'grid',
                         gridTemplateColumns: 'repeat(8, 2fr)',
                         gridTemplateRows: 'repeat(4, 1fr)', gap: '15px' }}>
                    {harpList.map((harp) => (
                        <Card
                            key={harp.id}
                            extra={<span className="harp-attributes">
                                {harp.attributes}
                            </span>}
                            onClick={() => handleCardClick(harp.id)} // 绑定点击事件
                        >
                            <p className="harp-one"
                               style={{ color: harp.attribute === 1 ? 'blue' : 'red' }}>
                                {harp.title}
                            </p>
                        </Card>
                    ))}
                </div>
            )}
        </div>
    );
};

export default HarpList;